# -*- coding: utf-8 -*-

"""
@File    : oss_utils.py
@Author  : xubin
@Time    : 2024/2/7 17:28
@Desc    :
"""
import io
import minio
from utils.tools import log
from funcs.config import (
    MINIO_ENDPOINT, MINIO_ACCESS_KEY, MINIO_SECRET_KEY, MINIO_SECURE)


class MinioClient:
    def __init__(self):
        self.client = minio.Minio(
            endpoint=MINIO_ENDPOINT,
            access_key=MINIO_ACCESS_KEY,
            secret_key=MINIO_SECRET_KEY,
            secure=MINIO_SECURE,
        )

    def bucket_exists(self, bucket_name: str):
        return self.client.bucket_exists(bucket_name=bucket_name)

    def create_bucket(self, bucket_name: str):
        try:
            if not self.bucket_exists(bucket_name):
                self.client.make_bucket(bucket_name=bucket_name)

        except Exception as e:
            log.error(f"Error creating bucket {bucket_name}: {e}")

    def upload_data(
        self,
        bucket: str,
        object_name: str,
        file_path: str,
        content_type="application/octet-stream",
    ):
        try:
            self.create_bucket(bucket)
            self.client.fput_object(
                bucket_name=bucket,
                object_name=object_name,
                file_path=file_path,
                content_type=content_type,
            )
        except Exception as e:
            log.error(f"Error uploading to {bucket}/{object_name}: {e}")

    def upload_obj(
        self,
        bucket: str,
        object_name: str,
        file_data,
        file_size,
        content_type="application/octet-stream",
    ):
        try:
            self.create_bucket(bucket)
            self.client.put_object(
                bucket_name=bucket,
                object_name=object_name,
                data=io.BytesIO(file_data),
                length=file_size,
                content_type=content_type,
            )
            log.success(f"Uploaded {object_name} to {bucket}")
            return True
        except Exception as e:
            log.error(f"Error uploading to {bucket}/{object_name}: {e}")

    def download_data(self, bucket: str, object_name: str):
        try:
            if not self.bucket_exists(bucket):
                return None
            data = self.client.get_object(bucket, object_name)
            return data.read()

        except Exception as e:
            log.error(f"Error downloading from {bucket}/{object_name}: {e}")
